package com.easyboot.web.system.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.easyboot.framework.properties.EasyBootConfig;
import com.easyboot.utils.IdHelper;
import com.easyboot.utils.MimeTypeUtils;
import com.easyboot.utils.log.LoggerHelper;
import com.easyboot.constant.CookieConstants;
import com.easyboot.framework.shiro.UserOwnInfo;
import com.easyboot.framework.core.ActionResult;
import com.easyboot.framework.core.BaseController;
import com.easyboot.framework.domain.DataTableDto;
import com.easyboot.framework.domain.ResultAdaptDto;
import com.easyboot.framework.domain.KeyValueInt64Dto;
import com.easyboot.framework.core.RequestHelper;
import com.easyboot.web.system.domain.SysUser;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import com.easyboot.web.system.service.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/admin/sysuser")
public class SysUserController extends BaseController {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private RequestHelper requestHelper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysPositionService positionService;
    @Autowired
    private EasyBootConfig easyCmsConfig;
    /**
    *
     * @author yushuo
     * @description 用户页面
     * @date 15:00 2021/1/29
     * @param
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/index")
    @RequiresPermissions("system:user:view")
    public ActionResult index(){

        return view();
    }

    /**
    *
     * @author yushuo
     * @description 用户列表
     * @date 15:01 2021/1/29
     * @param loginName: 用户登录名
     * @return com.easyboot.framework.domain.DataTableDto
    **/
    @PostMapping("/getUserList")
    @RequiresPermissions("system:user:view")
    public ActionResult getUserList(@ModelAttribute DataTableDto dto, @RequestParam String loginName, @RequestParam String userName,@RequestParam String phone)
    {
        dto= sysUserService.getUserList(dto,loginName,userName,phone);
        return json(dto);
    }

    /**
    *
     * @author yushuo
     * @description //新增，修改
     * @date 13:59 2021/2/6
     * @param [id, model]
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/form")
    @RequiresPermissions(value = {"system:user:add","system:user:edit"},logical = Logical.OR)
    public ActionResult form(String id, ModelMap model){

        List<KeyValueInt64Dto> roles=roleService.getRoles();
        List<KeyValueInt64Dto> positions =positionService.getPositionSelectList();
        model.put("id",id);
        model.put("roles",roles);
        model.put("positions",positions);
        return view();
    }

    /**
    *
     * @author yushuo
     * @description //获取用信息
     * @date 13:59 2021/2/6
     * @param [id]
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/getModel")
    @RequiresPermissions(value={"system:user:add","system:user:edit"},logical=Logical.OR)
    public ActionResult getModel(String id){
        ResultAdaptDto result=new ResultAdaptDto();
        if(StrUtil.isEmpty(id)|| "0".equals(id)){
            return error("用户信息不存在");
        }

        SysUser user=sysUserService.getModel(Convert.toLong(id));
        if(user==null){

            return error("用户信息不存在");
        }

        result.getData().put("model",user);
        return json(result);
    }

    /**
    *
     * @author yushuo
     * @description //保存数据
     * @date 13:58 2021/2/6
     * @param [dto]
     * @return com.easyboot.framework.web.ActionResult
    **/
    @PostMapping("/save")
    @RequiresPermissions(value={"system:user:add","system:user:edit"},logical=Logical.OR)
    public ActionResult save(SysUser dto){
        if(StrUtil.isEmpty(dto.getUserName())||StrUtil.isEmpty(dto.getPassWord())){
            return error("用户名密码验证失败");
        }
        String[] position=requestHelper.getStringArray("position");

        boolean userExists= sysUserService.userExists(dto);
        if(userExists){
            return error(StrUtil.format("登录账号[{}]已存在",dto.getLoginName()));
        }
        sysUserService.save(dto,position,requestHelper.getUserOwnInfo());
        return ok("用户保存成功");
    }

    /**
    *
     * @author yushuo
     * @description //删除
     * @date 13:58 2021/2/6
     * @param [ids]
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/removeAll")
    @RequiresPermissions("system:user:delete")
    public ActionResult removeAll(String ids){
        if(StrUtil.isEmpty(ids)){
            return error("参数验证失败");
        }
         sysUserService.removeAll(ids);
        return ok("删除成功");
    }

    /**
    *
     * @author yushuo导出用户信息//TODO
     * @date 10:50 2021/7/6
     * @param [response]
     * @return void
    **/
    @RequiresPermissions("system:user:export")
    @GetMapping("/exportUser")
    public void ExportUser(HttpServletResponse response){
            DataTableDto dto=new DataTableDto();
            dto.setPageNumber(1);
            dto.setPageSize(100);
        dto=sysUserService.getUserList(dto,"","","");
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户信息表", "测试"),SysUser.class, dto.getRows());
        downLoadExcel("EasyBoot用户信息表.xlsx",workbook,response);
    }

    @GetMapping("/UserCount")
    @ResponseBody
    public String userCount(){
        Long total=jdbcTemplate.queryForObject("select count(*) from sys_user",Long.class);

        return total.toString();
    }


    /**
    *
     * @author 用户选择界面
     * @description //TODO
     * @date 15:13 2021/2/26
     * @param []
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/userSelect")
    public ActionResult userSelect(){
        return view();
    }

    /**
    *
     * @author yushuo
     * @description 个人资料
     * @date 10:13 2021/2/27
     * @param []
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/profile")
    public ActionResult profile(Model model){

        UserOwnInfo userOwnInfo= requestHelper.getUserOwnInfo();
        //LoggerHelper.console("部门信息为："+userOwnInfo.getDeptName());
        String postGroup= positionService.getUserPositonsName(userOwnInfo.getId());
        String loginIp=requestHelper.getIp();
        model.addAttribute("user",userOwnInfo);
        model.addAttribute("postGroup",postGroup);
        model.addAttribute("loginIp",loginIp);
        return view();
    }

    /**
    *
     * @author yushuo
     * @description 更新个人资料
     * @date 11:00 2021/2/27
     * @param []
     * @return com.easyboot.framework.web.ActionResult
    **/
    @PostMapping("/updateProfile")
    public ActionResult updateProfile(HttpServletResponse response){

        long id=requestHelper.getInt64("id",0L);
        String userName=requestHelper.getString("userName","");
        String mobilePhone=requestHelper.getString("mobilePhone","");
        String email=requestHelper.getString("email","");
        String gender=requestHelper.getString("gender","2");
        ResultAdaptDto resultAdaptDto= sysUserService.updateProfile(id,userName,mobilePhone,email,Convert.toInt(gender));
        if(resultAdaptDto.isStatus()){
            UserOwnInfo userOwnInfo= requestHelper.getUserOwnInfo();
            userOwnInfo.setUserName(userName.trim());
            userOwnInfo.setMobilePhone(mobilePhone.trim());
            userOwnInfo.setEmail(email.trim());
            userOwnInfo.setGender(gender.trim());

           requestHelper.setUserCookie(userOwnInfo,response);

        }
        return json(resultAdaptDto);
    }

    /**
     *
     * @author yushuo
     * @description 更新密码
     * @date 11:00 2021/2/27
     * @param []
     * @return com.easyboot.framework.web.ActionResult
     **/
    //@RequiresPermissions("system:user:password")
    @GetMapping("/resetPasswordView")
    public ActionResult resetPasswordView(Model model){
        String id=requestHelper.getString("id","0");
        String loginName=requestHelper.getString("loginName","");
        if("0".equals(id)){
            UserOwnInfo userOwnInfo= requestHelper.getUserOwnInfo();
            id=userOwnInfo.getId().toString();
            loginName=userOwnInfo.getLoginName();

        }
        model.addAttribute("id",id);
        model.addAttribute("loginName",loginName);
        return view();
    }

    /**
     *
     * @author yushuo
     * @description 更新密码
     * @date 11:00 2021/2/27
     * @param []
     * @return com.easyboot.framework.web.ActionResult
     **/
    @PostMapping("/updatePassword")
    public ActionResult updatePassword(){
        long id=requestHelper.getInt64("id",0L);
        String oldPassword=requestHelper.getString("oldPassword","");
        String newPassword=requestHelper.getString("newPassword","");
        String accountName=requestHelper.getString("loginName","");
        ResultAdaptDto resultAdaptDto= sysUserService.updatePassword(id,accountName,oldPassword,newPassword);
        return json(resultAdaptDto);
    }

    /**
    *
     * @author yushuo
     * @description 更新头像
     * @date 14:54 2021/7/5
     * @param []
     * @return com.easyboot.framework.core.ActionResult
    **/
    @GetMapping("/avatar")
    public ActionResult avatar(ModelMap model){
        UserOwnInfo userOwnInfo= requestHelper.getUserOwnInfo();

        model.addAttribute("avatar",userOwnInfo.getAvatar());
        return view();
    }


    /**
    *
     * @author yushuo
     * @description 上传头像
     * @date 14:55 2021/7/5
     * @param []
     * @return com.easyboot.framework.core.ActionResult
    **/
    @PostMapping("/updateAvatar")
    public ActionResult updateAvatar(@RequestParam("avatarfile") MultipartFile file,HttpServletResponse response){
        if(file.isEmpty()) {
            return error("请选择文件");
        }

        try{


        String avatorFolder=easyCmsConfig.getAvatarPath();
        File directory  = new File(avatorFolder);
        if(!directory.exists()){
            directory.mkdirs();
        }
        String newFileName = IdHelper.objectId() +"."+ MimeTypeUtils.getExtension(file.getContentType());
        String absolutePath = directory.getAbsolutePath(); //获取绝对路径
        File uploadpath = new File(absolutePath + File.separator + newFileName);
        file.transferTo(uploadpath);



            String ralPath="/uploads/avatar/"+newFileName;
            UserOwnInfo userOwnInfo= requestHelper.getUserOwnInfo();
            sysUserService.updateAvatar(userOwnInfo.getId(),ralPath);
            userOwnInfo.setAvatar(ralPath.trim());

            requestHelper.setUserCookie(userOwnInfo,response);

            ResultAdaptDto result =new ResultAdaptDto();
            result.put("file",ralPath);
            return json(result);
        }catch(Exception e){
           LoggerHelper.error(e);
        }
        return error("头像更新失败");
    }
}
